<%@ page contentType="text/html;charset=UTF-8" language="java"
	pageEncoding="utf-8"%>
<%@ include file="../include/head.jsp"%>
<%@ include file="../include/top.jsp"%>
<%@ include file="../include/left.jsp"%>
<div class="main-content">

	<%@ include file="../include/navigate.jsp"%>
	<div class="container">
		<div class="row clearfix ">

			<div class="col-md-12 last">
				<div id="errorMsg" class="alert alert-danger alert-dismissable">
					<button type="button" class="close" data-dismiss="alert"
						aria-hidden="true">×</button>
					<p></p>
				</div>
				<c:if test="${error != null }">
					<div class="alert alert-danger alert-dismissable">
						<button type="button" class="close" data-dismiss="alert"
							aria-hidden="true">×</button>
						<strong>异常:</strong> ${error}
					</div>
				</c:if>
				<c:if test="${msg != null }">
					<div class="alert alert-info alert-dismissable">
						<button type="button" class="close" data-dismiss="alert"
							aria-hidden="true">×</button>
						<strong>提示:</strong> ${msg}
					</div>
				</c:if>
				<div id="saveStatus"></div>
				<div class="widget-box">
					<div class="widget-box-header">
						<div class="col-sm-9">
							<div class="title">定时调度作业列表</div>
						</div>
						<div class="col-sm-3" align="right" style="margin-top: 2px; text-align:right;">
							 
							<div class="btn-group-sm" style="padding:2px;">
								<!--  
								<c:if test="${sessionScope.validUrls.contains('/cronJob/add')}">
			                        <a type="button" class="btn btn-default btn-sm glyphicon glyphicon-plus" onclick="addRow()" id="addRowButton"> 新增
			                        </a>
		                        </c:if>
		                        -->
		                        
		                        <a type="button" class="btn btn-default btn-sm glyphicon glyphicon-plus" onclick="window.location='${pageContext.request.contextPath}/cronJob/add'"> 新增</a>
		                    </div>

						</div>
					</div>

					<div class="widget-box-content" style="padding:15px;">
						<div class="dataTables_wrapper form-inline"
							style="height: 550px; overflow: auto">
							<div class="table-responsive">
								<table id="jobTable" class="tableComponent table table-hover"
									width="100%">
									<thead>
										<tr>
											<th>etl作业</th>
											<th>任务名称</th>
											<th>操作用户</th>
											<th>cron表达式</th>
											<th>描述</th>
											<th>状态</th>
											<th>操作</th>
										</tr>
									</thead>
									<tbody id="cronJobList">

										<c:forEach items="${scheduleJobs}" var="job" varStatus="idx">
											<c:set var="trClass" value="${job.enable == 'false'? 'danger':'success'}"></c:set>
											<tr class='<c:out value="${trClass}" />'>
												<c:forEach items="${jobs}" var="etlJob">
													<c:if test="${etlJob.xmlJobId == job.etlXmlId}"> 
														<c:set var="jobName" value="${etlJob.xmlJobName}"></c:set>
													</c:if>
												</c:forEach>
												<td><kbd>${jobName}</kbd></td>
												<td><kbd>${job.jobNameDisplay}</kbd></td>
												<td>${idNameMap[job.setupUserId]}</td>
												<td>${job.cronExpression}</td>
												<td>${job.des}</td>
												<td>
													<c:if test="${job.enable == 'true'}">
														<c:if test="${job.jobStatus == '1'}">
														    等待调度。下次执行时间是：<fmt:formatDate value="${job.nextExecuteTime}" pattern="YYYY-MM-dd HH:mm:ss"/>
														</c:if>
														<c:if test="${job.jobStatus == '2'}">
														    正在执行...
														</c:if>
													</c:if>
													<c:if test="${job.enable == 'false'}">
														未启用
													</c:if>
												</td>
												<td>
													<div class="btn-group">
														<c:if test="${sessionScope.validUrls.contains('/cronJob/startJob')}">
															<c:if test="${job.enable eq true}">
																<a class="btn btn-warning" jobId='${job.jobId}' onclick='turnStatus(this)'>停用</a>
															</c:if>
															<c:if test="${job.enable eq false}">
																<a class="btn btn-success" jobId='${job.jobId}' onclick='turnStatus(this)'>启用</a>
															</c:if>
														</c:if>
														<%-- <a class="btn btn-primary" jobId='${job.jobId}' onclick="editJobConfig(this, ${job.jobId})">修改</a> --%>
														<c:if test="${sessionScope.validUrls.contains('/cronJob/deleteJob')}">
															<button type="button" class="btn btn-danger" onclick="openModal('${pageContext.request.contextPath}/cronJob/deleteJob?page=${page}&jobId=${job.jobId}','删除任务？','被删除任务将无法恢复，确定删除？')">删除</button>
														</c:if>
														<c:if test="${!sessionScope.validUrls.contains('/cronJob/deleteJob') && !sessionScope.validUrls.contains('/cronJob/startJob')}">
															无
														</c:if>
													</div>
												</td>
											</tr>
										</c:forEach>
									</tbody>
								</table>
							</div>
						</div>

						<div class="row clearfix" align="center">
							<div class="col-md-12">
								<nav>
									<ul class="pagination pagination-sm">
									</ul>
								</nav>
							</div>
						</div>

					</div>


				</div>

			</div>

		</div>
	</div>

<script type="text/javascript">
/*

字段名                 允许的值                        允许的特殊字符  
秒                     0-59                            , - * /  
分                     0-59                            , - * /  
小时                    0-23                           , - * /  
日                     1-31                            , - * ? / L W C  
月                     1-12 or JAN-DEC                 , - * /  
周几                   1-7 or SUN-SAT                   , - * ? / L C #  
年 (可选字段)           empty,1970-2099                 , - * /



“?”字符：表示不确定的值

“,”字符：指定数个值

“-”字符：指定一个值的范围

“/”字符：指定一个值的增加幅度。n/m表示从n开始，每次增加m

“L”字符：用在日表示一个月中的最后一天，用在周表示该月最后一个星期X

“W”字符：指定离给定日期最近的工作日(周一到周五)

“#”字符：表示该月第几个周X。6#3表示该月第3个周五

*/
function addInputMask(){
	$('.input-mask-jobName').inputmask('a{6,}', {
		onincomplete : function() {
			$('#username_tips').prop("hidden", false);
		},
		oncomplete : function() {
			$('#username_tips').prop("hidden", true);
		},
		clearMaskOnLostFocus: false,
		insertMode: true
	});
	
	Inputmask.extendDefinitions({
		'c': {
		    validator: "[0-9*/\,\-]", // 有效输入字符：0-9 * / , -
		    cardinality: 1,
		    casing: "upper" //auto uppercasing
		},
		'm': {      // 月份字段可接受字符
		    validator: "[0-9a-zA-Z*/\,\-]", // 有效输入字符：0-9 a-z A-Z * / , -
		    cardinality: 1,
		    casing: "upper" //auto uppercasing
		},
		'd': {      // day
		    validator: "[0-9*/?\,\-LWClwc]", // 有效输入字符：0-9 * / , - ? L W C l w c
		    cardinality: 1,
		    casing: "upper" //auto uppercasing
		},
		'w': {      // week
		    validator: "[1-7a-zA-Z*/?\,\-]", // 有效输入字符：1-7 * / , - 
		    cardinality: 1,
		    casing: "upper" //auto uppercasing
		}
	});
	
	$('.input-mask-cronExp').inputmask('c{1,} c{1,} c{1,} d{1,} m{1,} w{1,} c{0,}', {
		clearMaskOnLostFocus: false,
		insertMode: true
	});
}
</script>

	<script type="text/javascript">
        $('.pagination').twbsPagination({
            totalPages: ${pageInfo.pages},
            visiblePages: 5,
            href: '?page={{number}}'
        });
        
        $(document).ready(function(){
        	window.addRow = function(){
        		if($("#addNew").length > 0) return;
        		$("#cronJobList").append("<tr id='addNew'>" + 
        								     "<td>" + 
        								         "<select id='etlId' class='form-control'>" + 
        								             "<option value='-1'>请选择...</option>" + 
        								             "<option value='0'>层级1</option>" + 
        								             "<option>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;更新任务</option>" + 
        								         "</select>" + 
        								     "</td>" + 
        				                     "<td><input id='jobName' type='text' class='input-mask-jobName' name='jobName' placeholder='请输入作业名称' data-toggle='tooltip' data-placement='left' required=''></td>" + 
        								     "<td><input id='cronExp' type='text' class='input-mask-cronExp' name='cronExp' placeholder='*  *  *  *  *' data-toggle='tooltip' data-placement='left' required=''></td>" + 
        								     "<td><input id='des' type='text' class='form-control' name='cronJobId' placeholder='请添加作业描述' data-toggle='tooltip' data-placement='left' required=''></td>" +
        								     "<td><input type='checkbox' id='startNow'>是否立刻启用</input></td>" + 
        								     "<td><button type='button' onclick='saveRow()' class='btn btn-primary'>保存</button><button type='button' onclick='cancelRow()' class='btn btn-danger'>取消</button></td>" + 
        								 "</tr>");
        		
        		$("#addRowButton").addClass("disabled");
        		addInputMask();
        	};
        	
        	window.cancelRow = function(){
        		$("#addNew").remove();
        		$("#addRowButton").removeClass("disabled");
        	};
        	
        	window.editJobConfig = function(button, jobId){
        	};
        	
        	window.deleteJob = function(button, jobId){
        		
        		var ii = openModal('','删除任务?','删除的任务将无法恢复，是否继续?');
        		console.log(ii);
        		
    			$.ajax({  
		        	type:'post',
		            url: '/cronJob/deleteJob',
		            data: {"jobId": jobId},  
		            async: false,
		            cache:false,    
		            dataType:'json',    
		            success: function(data) {
		            	if(data != 'success'){
		            		operationFailedWithMessage(data);
		            	} else {
		            		$(button).closest("tr").remove();
		            	}
		            },    
		            error : function() {
		            	operationFailed();
		            }
		        });
        	};
        	
        	window.turnStatus = function(button){
        		if($(button).text() == '启用'){
        			var startOK = true;
        			var date;
        			$.ajax({  
    		        	type:'post',
    		            url: '/cronJob/startJob',
    		            data: {"jobId": $(button).attr("jobId"), enable: 1},  
    		            async: false,
    		            cache:false,    
    		            dataType:'json',    
    		            success: function(data) {
    		            	if(data.substr(0, 7) != 'success'){
    		            		operationFailedWithMessage(data);
    			                startOK = false;
    		            	}
    		            	
    		            	date = data.replace("success", "");
    		            },    
    		            error : function() {
    		            	operationFailed();
    		                startOK = false;
    		            }
    		        });
        			
        			if(!startOK){
        				return;
        			}
        			
        			$(button).removeClass("btn-success");
        			$(button).addClass("btn-warning");
        			$(button).text("停用");
        			$(button).closest("tr").removeClass('danger');
        			$(button).closest("tr").addClass('success');
        			$(button).closest("td").prev().text("等待执行。下次执行时间是：" + date);
        		} else {
        			var stopOK = true;
        			$.ajax({
    		        	type:'post',
    		            url: '/cronJob/startJob',
    		            data: {"jobId": $(button).attr("jobId"), enable: 0},  
    		            async: false,
    		            cache:false,    
    		            dataType:'json',    
    		            success: function(data) {
    		            	if(data.substr(0, 7) != 'success'){
    			                operationFailedWithMessage(data);
    			                stopOK = false;
    		            	}
    		            },    
    		            error : function() {
    		            	operationFailed();
    		                stopOK = false;
    		            }
    		        });
        			
        			if(!stopOK){
        				return;
        			}
        			$(button).removeClass("btn-warninig");
        			$(button).addClass("btn-success");
        			$(button).text("启用");
        			$(button).closest("tr").removeClass('success');
        			$(button).closest("tr").addClass('danger');
        			$(button).closest("td").prev().text("未启用");
        		}
        	}
        	
        	window.saveRow = function(){
        		var etlId = $("#etlId").val();
        		var jobName = $("#jobName").val();
        		var exp = $("#cronExp").val();
        		var isStartNow = $("#startNow").prop("checked");
        		var des = $("#des").val();
        		
        		if(etlId == "-1" || etlId == "0" || jobName == "" || exp == "" || des == ''){
        			alert("输入框不能为空");
        			return;
        		}
        		
        		var serverOK = true;
        		
        		var jobId = '';
        		$.ajax({  
		        	type:'post',
		            url: '/cronJob/add',
		            data: {"jobNameDisplay": jobName, "cronExpression": exp, "etlXmlId": 1, "enable": isStartNow, "des": des},  
		            async: false,
		            cache:false,    
		            dataType:'json',    
		            success: function(data) {
		            	if(data.substr(0, 7) != 'success'){
		            		
		            		jobId = data.split('-------')[0];
		            		var message = data.split('-------')[1];
		            		
		            		operationFailedWithMessage(message);
			                isStartNow = false;
		            	} else {
		            		jobId = data.replace("success", "");
		            	}
		            },    
		            error : function() {
		            	operationFailed();
		                serverOK = false;
		                isStartNow = false;
		            }
		        });	
        		
        		if(!serverOK){
        			return;
        		}
        		
        		var trClass = '';
        		var status = '';
        		var buttonClass = '';
        		var buttonText = '';
        		var buttonStatus = 0;
        		if(isStartNow == true){
        			trClass = 'success';
        			buttonClass = 'warning';
        			buttonText = '停用';
        			buttonStatus = 0;
        			status = '等待执行。';
        		} else {
        			trClass = 'danger';
        			buttonClass = 'success';
        			buttonText = '启用';
        			buttonStatus = 1;
        			status = '未启用';
        		}
        		
        		$("#addNew").remove();
        		$("#cronJobList").append("<tr class='" + trClass + "'>" + 
										      "<td><kbd>" + etlId + "</kbd></td>" + 
										      "<td><kbd>" + jobName + "</kbd></td>" + 
										      "<td>" + exp + "</td>" + 
										      "<td>" + des + "</td>" +
										      "<td>" + status + "</td>" +
										      "<td>" + 
										          "<a class='btn btn-" + buttonClass + "' onclick='turnStatus(" + buttonStatus + ")' jobId='" + jobId + "'>" + buttonText + "</a>" +
										          // "<a class='btn btn-primary' jobId='" + jobId + "' onclick='editJobConfig(this, " + jobId + ")'>修改</a>" +
												  "<button type='button' class='btn btn-danger' onclick=\"openModal('${pageContext.request.contextPath}/cronJob/deleteJob?page=${page}&jobId=" + jobId + "','删除任务？','被删除任务将无法恢复，确定删除？')\">删除</button>" +
										      "</td>" + 
										  "</tr>");
        		$("#addRowButton").removeClass("disabled");
        	}
        });
    </script>

	<div style="position: fixed; bottom: 0; width: 100%;" align="center">
		<%@ include file="../include/footer.jsp"%>
	</div>
</div>
<%@ include file="../include/bottom.jsp"%>
